#!/GPUFS/app_GPU/application/anaconda3/5.3.1/envs/python-3.6/bin/python
import os
import os.path
import glob
import bson
from pymongo import MongoClient

root_path = '/GPUFS/igsnrr_czqin_2/shenshen/dump/'
target_mongodb_ip = '10.108.221.136'
client = MongoClient(target_mongodb_ip)

subdirs = os.listdir(root_path)
print('Database: ' + ','.join(subdirs))
# 注意这里会删除数据库，请dump数据库中的所有collection
for dir in subdirs:
    # new database
    if dir in client.list_database_names():
        client.drop_database(dir)
        print('drop database {0} first'.format(dir))
    newdb = client[dir]
    content_path = root_path + dir
    for bf in glob.glob(content_path + '/*.bson'):
        print(bf)
        col_name = os.path.splitext(os.path.basename(bf))[0]
        with open(bf, 'rb') as fp:
            coll_raw = fp.read()
        coll = bson.decode_all(coll_raw)
        newdb.create_collection(col_name)
        newdb[col_name].insert_many(coll)
        print('import {0} successfully!'.format(col_name))
